<template>
  <LoadingWrapper :loading="loading">
    <div class="crawler">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>爬虫管理</span>
            <el-button type="primary" @click="showConfirm" :loading="crawling">
              开始爬取
            </el-button>
          </div>
        </template>

        <el-form :model="form" label-width="100px" ref="formRef">
          <el-form-item 
            label="目标URL" 
            prop="url"
            :rules="[
              { required: true, message: '请输入目标URL', trigger: 'blur' },
              { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
            ]"
          >
            <el-input 
              v-model="form.url" 
              placeholder="请输入要爬取的URL"
              :disabled="crawling"
              clearable
            >
              <template #append>
                <el-tooltip content="点击使用默认URL">
                  <el-button @click="useDefaultUrl">
                    <el-icon><RefreshLeft /></el-icon>
                  </el-button>
                </el-tooltip>
              </template>
            </el-input>
          </el-form-item>
        </el-form>

        <div class="status" v-if="crawling">
          <el-progress 
            :percentage="progress" 
            :status="progress >= 100 ? 'success' : ''"
            :stroke-width="15"
          />
          <p class="status-text">{{ statusText }}</p>
        </div>
      </el-card>
    </div>

    <!-- 确认对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="确认爬取"
      width="30%"
      :close-on-click-modal="false"
    >
      <span>确定要开始爬取数据吗？此操作可能需要一些时间。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </LoadingWrapper>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { RefreshLeft } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { triggerCrawl } from '@/api/article'
import { handleError, handleSuccess } from '@/utils/error-handler'
import LoadingWrapper from '@/components/LoadingWrapper.vue'

const DEFAULT_URL = 'https://m.kantao.cn/'

const formRef = ref<FormInstance>()
const form = ref({
  url: DEFAULT_URL
})

const loading = ref(false)
const crawling = ref(false)
const progress = ref(0)
const dialogVisible = ref(false)

const statusText = computed(() => {
  if (progress.value >= 100) {
    return '爬取完成'
  }
  return '正在爬取中，请稍候...'
})

let progressTimer: number | null = null

function startProgress() {
  progress.value = 0
  progressTimer = setInterval(() => {
    if (progress.value < 90) {
      progress.value += 10
    }
  }, 1000)
}

function stopProgress(success = true) {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
  progress.value = success ? 100 : progress.value
  crawling.value = false
}

function useDefaultUrl() {
  form.value.url = DEFAULT_URL
}

async function showConfirm() {
  // 表单验证
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    dialogVisible.value = true
  } catch (error) {
    handleError(new Error('请检查表单填写是否正确'))
  }
}

async function handleConfirm() {
  dialogVisible.value = false
  crawling.value = true
  loading.value = true
  startProgress()
  
  try {
    await triggerCrawl(form.value.url)
    handleSuccess('爬虫任务已启动')
    stopProgress(true)
  } catch (error) {
    handleError(error)
    stopProgress(false)
  } finally {
    loading.value = false
  }
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (progressTimer) {
    clearInterval(progressTimer)
  }
})
</script>

<style scoped lang="scss">
.crawler {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .status {
    margin-top: 20px;
    
    .status-text {
      margin-top: 10px;
      color: #909399;
      text-align: center;
    }
  }
  
  :deep(.el-progress-bar__outer) {
    background-color: #e9ecef;
  }
  
  :deep(.el-progress-bar__inner) {
    transition: width 0.3s ease;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 